/**
 * Created by LMN on 2016/7/14.
 * ORM of MySQL.
 */
var Sequelize = require('sequelize');
var conf = require('../config');
var sequelize = new Sequelize(conf.mysql.database, conf.mysql.uname,conf.mysql.passwd, {
    host : conf.mysql.host,
    port : conf.mysql.port,
    dialect : 'mysql',
    pool: {
        maxConnections: 200,
        minConnections: 20,
        maxIdleTime: 2000
    },
    timezone: '+08:00',
    logging: false,
    maxConcurrentQueries: 100
});

var user = sequelize.define('user',{
    username: {
        type: Sequelize.STRING,
        primaryKey: true
    },
    password: Sequelize.STRING,
    auth: Sequelize.INTEGER
});

var station = sequelize.define('station', {
    code: {
        type: Sequelize.STRING,
        primaryKey: true
    },
    port: {
        type: Sequelize.INTEGER,
        allowNull: false
    },
    type: Sequelize.INTEGER,
    latitude: {type:Sequelize.DOUBLE,allowNull:false},
    longitude: {type:Sequelize.DOUBLE,allowNull:false},
    altitude: {type:Sequelize.DOUBLE,allowNull:false},
    state: {type:Sequelize.INTEGER, defaultValue: 0}
},{
    timestamps: false,
    indexes: [{
        fields: ['type']
    },{
        fields: ['port']
    }]
});

var userStation = sequelize.define('user_station',{

},{
    timestamps: false
});
//One user has many station.
user.belongsToMany(station,{ through: userStation});
station.belongsToMany(user,{ through: userStation});

var event = sequelize.define('event', {
    type: Sequelize.INTEGER
});
//One user has many event.
event.belongsTo(user);user.hasMany(event);

var pa = sequelize.define('pose_actual',{
    time: {type:Sequelize.DATE,allowNull:false},
    mark: {type:Sequelize.INTEGER,allowNull:false},
    accuracy: {type:Sequelize.DOUBLE,allowNull:false},
    latitude: {type:Sequelize.DOUBLE,allowNull:false},
    longitude: {type:Sequelize.DOUBLE,allowNull:false},
    altitude: {type:Sequelize.DOUBLE,allowNull:false},
    speed: {type: Sequelize.FLOAT, allowNull:true}
});
//One user has many actual data.
pa.belongsTo(user);user.hasMany(pa);

sequelize.sync();

module.exports = {
    station: station,
    us: userStation,
    event: event,
    poseActual: pa,
    user: user,
    Seq: Sequelize,
    seq: sequelize
};